package cn.liyicun.cp.cpweb.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.liyicun.cp.cpweb.base.Result;
import cn.liyicun.cp.cpweb.entity.GetApicp;
import cn.liyicun.cp.cpweb.service.SettingInfoService;
import cn.liyicun.cp.cpweb.service.cp.GetApicpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
public class SyncDataController extends BaseController {

    private static transient Logger logger = LoggerFactory.getLogger(SyncDataController.class);
    @Autowired
    GetApicpService getApicpService;

    @Autowired
    private SettingInfoService settingInfoService;

    @RequestMapping(value = "/sync/{code}")
    public Result<?> sync(@PathVariable String code, @RequestParam String name, @RequestParam String opencode,
                          @DateTimeFormat(pattern = DatePattern.NORM_DATETIME_PATTERN) @RequestParam Date opentime, @RequestParam String expect, HttpServletRequest request) {

        String ip = HttpUtil.getClientIP(request);


        if ("none".equals(code)) {
            settingInfoService.clear();
            return null;
        }
        compare(!settingInfoService.containsKeyCache("sync", ip), "不是白名单:" + ip);


        GetApicp data = new GetApicp();
        data.setCode(code);
        data.setName(name);
        data.setOpencode(opencode);
        data.setOpentime(opentime);
        data.setExpect(expect);
        logger.info("ip:{},code:{},data:{}", ip, code, JSONUtil.parse(data));
        getApicpService.one(data);
        return Result.success(code);
    }
}
